<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-17 09:38:14
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-03-17 17:25:03
 * @FilePath: \vprisk10.14\src\views\PublicManage\publicManage\currencyManage.vue
 * @Description: 币种管理
-->
<template>
  <!-- 币种管理页面 -->
  <div>
    <el-row class="currencyManage container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.currencyCode = ''), (searchForm.currencyName = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addFunc()">新增</el-button>
            <el-button @click="editFunc()">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="enable('1')">启用</el-button>
            <el-button @click="enable('0')">停用</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="87px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="币种编码：">
                <el-input
                  v-model="searchForm.currencyCode"
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="币种名称：" prop="treeTypeName">
                <el-input
                  v-model="searchForm.currencyName"
                  style="width:150px"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="currencyCode"
            label="编号"
            v-if="columnState[0]"
             show-overflow-tooltip 
          >
          </el-table-column>
          <el-table-column
            prop="currencyName"
            label="名称 "
            v-if="columnState[1]"
             show-overflow-tooltip 
          >
          </el-table-column>

          <el-table-column
            prop="currencyFlag"
            label="是否为主币种 "
            v-if="columnState[2]"
            :formatter="row => (row.currencyFlag == 1 ? '是' : '否')"
          >
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态 "
            v-if="columnState[3]"
            :filter-method="(val, row) => row.status === val"
            :filters="[
              { text: '启用', value: '1' },
              { text: '停用', value: '0' }
            ]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == 1">
                <i class="startState"></i><span>启用</span>
              </div>
              <div v-if="scope.row.status == 0">
                <i class="unStartState"></i><span style="color:red">停用</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            sortable
            :formatter="row => row.creator || '-'"
            v-if="columnState[4]"
          >
          </el-table-column>
          <el-table-column
            prop="createdTm"
            label="创建时间"
            sortable
            v-if="columnState[5]"
             show-overflow-tooltip 
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            label="修改人"
            sortable
            v-if="columnState[6]"
            :formatter="row => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            label="修改时间"
            sortable
            v-if="columnState[7]"
             show-overflow-tooltip 
          >
            <template slot-scope="scope">
              <div v-if="scope.row.modifiedTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>

    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="币种编号：" prop="currencyCode" >
              <el-input
                v-model="saveForm.currencyCode"
                maxlength="3"
                :disabled="saveFlg == 2"
                placeholder="请输入币种编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="币种名称：" prop="currencyName" >
              <el-input
                v-model="saveForm.currencyName"
                maxlength="40"
                placeholder="请输入币种名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主币种标志：" prop="currencyFlag" >
              <el-select v-model="saveForm.currencyFlag" placeholder="请选择主币种标志"
              style="width:100%" :disabled='saveFlg==2&&editRow.currencyFlag=="1"'
              >
                <el-option
                  v-for="item in mgrRoleIdList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态：" prop="status">
              <el-select v-model="saveForm.status" placeholder="请选择状态"
              style="width:100%"
              disabled
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { publicManage_pub } from "@/api/index";
import { getDict } from "@/api/getDict";
import onlyOneSearch from "@/components/onlyOneSearch";
import moment from "moment";
export default {
  data() {
    return {
      userName: "", //右侧用户名
      userDo: "授权角色", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      isModuleData: false, //同步模块数据弹窗
      serachMore: false,
      isProConfig: false, //工程表配置弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["添加币种信息", "编辑币种信息"],
     
      statusList: [
        { value: "1", label: "启用" },
        { value: "0", label: "停用" }
      ],
      moduleDataForm: {},
      // 右侧树data
      treeData: [
        {
          id: 1,
          label: "一级 1",
          children: [
            {
              id: 4,
              label: "二级 1-1",
              children: [
                {
                  id: 9,
                  label: "三级 1-1-1"
                },
                {
                  id: 10,
                  label: "三级 1-1-2"
                }
              ]
            }
          ]
        },
        {
          id: 2,
          label: "一级 2",
          children: [
            {
              id: 5,
              label: "二级 2-1"
            },
            {
              id: 6,
              label: "二级 2-2"
            }
          ]
        },
        {
          id: 3,
          label: "一级 3",
          children: [
            {
              id: 7,
              label: "二级 3-1"
            },
            {
              id: 8,
              label: "二级 3-2"
            }
          ]
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 角色管理下拉框
      mgrRoleIdList: [],
      // search机构树悬停提示
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        currencyCode:"",
        currencyName:"",
        page: 1,
        size: 15
      },
      total: 100,
      saveForm: {
        currencyCode:"",
        currencyName:"",
        currencyFlag:"",
        status:"1"
      },
      searchFF: {},
      saveFormRules: {
        currencyCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[A-Z_]{3,3}$/,
            message: "只能输入3位的大写英文字母",
            trigger: "blur"
          },
          { validator: this.currencyCodeValid, trigger: "blur" },

        ],
        currencyName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,15}$/,
            message: "只能输入1-15位的汉字、字母、数字或括号",
            trigger: "blur"
          },
        ],
        currencyFlag: [
          { required: true, message: "请选择主币种标志", trigger: "blur" }
        ]
      },
      checkList: [],
      // 列隐藏
      textData: [
        { label: "币种编号" },
        { label: "币种名称 " },
        { label: "是否为主币种" },
        { label: "状态" },
        { label: "创建人 " },
        { label: "创建时间" },
        { label: "修改人 " },
        { label: "修改时间 " }
      ],
      // 获取table的数据
      tableData: [],
      //编辑行内数据暂存，供判断表单状态
      editRow:{}
    };
  },
  components: {
    onlyOneSearch
  },
  created() {
    this.checkListInit();
    this.searchFunc();
    this.getDict();
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    // this.getList();
  },
  watch: {
      addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    getDict() {
      getDict("ccyManage_flag").then(res => {
        console.log(res, "字典启用");
        if (res.code == 200) {
          this.mgrRoleIdList = res.datas;
        }
      });
    },
    searchFunc() {
      let data = this.searchForm;
      publicManage_pub.currencyManageQuery(data).then(res => {
        this.tableData = res.data.sort((x,y)=>{return y.currencyFlag-x.currencyFlag});
        this.total = res.count;
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.saveForm.status = '1'
      this.saveForm.currencyFlag = '0'
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.editRow = form;
      this.saveForm = form;
      this.addOrEdit = true;
    },
    // 编号是否重复校验
    currencyCodeValid(rule, value, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      publicManage_pub
        .currencyManagecheckCurrencyCodeUnique({ currencyCode: value })
        .then(res => {
          if (res.success) {
            callback(new Error("编号已存在"));
          } else {
            callback();
          }
        });
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          publicManage_pub.currencyManageSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中币种吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let delFlag = true
          for (let i = 0; i < selection.length; i++) {
            if(selection[i].currencyFlag=='1'){
              delFlag = false;
              break;
            }
          }
            if(!delFlag) return this.$message.warning("主币种不允许删除")
          let data = { ids: selection.map(v => v.currencyCode) };
          publicManage_pub.currencyManageRemove(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    enable(data) {
      let val = data == "1" ? "启用" : "停用";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要" + val + "的币种");
      }
      this.$confirm(`您确定要${val}所选币种吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let alow = true
          for (let i = 0; i < selection.length; i++) {
            if(selection[i].currencyFlag=='1'){
                alow = false
            }
          }
          if(!alow)return this.$message.warning("主币种不可改变状态")
          let data = {
            ids: selection.map(v => v.currencyId),
            status: val == "启用" ? "1" : "0"
          };
          publicManage_pub.currencyManageUpdateStatus(data).then(res => {
            if (res.code == 200) {
              this.$message.success(val + "成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || val + "失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + val
          });
        });
    },
    handleNodeClick() {
      let nodes = this.$refs.configTree.getCheckedNodes();
      console.log(nodes);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    getList() {
      publicManage_pub.query("我的参数").then(res => {
        console.log(res);
      });
    },
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
      }
      this.userName = row.roleName;
    },
    // 重新加载
    reload() {
      this.isModuleData = true;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>